<script setup>
import {onMounted} from 'vue'
import {
  NAvatar,
  NButton,
  NFlex,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSelect,
  NTabPane,
  NTabs,
  NTag,
  useMessage,
  useDialog
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import api from '@/api'
import default_image from "@/assets/images/mz.jpg";
const dialog = useDialog();
import {getToken, renderIcon} from "@/utils";
import TheIcon from "@/components/icon/TheIcon.vue";
import {useCRUD} from "@/composables";
import CrudModal from "@/components/table/CrudModal.vue";
const base_path = import.meta.env.VITE_BASE
const message = useMessage()
const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '病例',
  initForm: {},
  doCreate: api.createOrder,
  doDelete: api.deleteOrder,
  doUpdate: api.updateOrder,
  refresh: () => on_ref(),
})

const props = defineProps({
  infoData: {
    type: Object,
    required: true
  }
});
const data = reactive({
    orders:[],
    card_loading:false,
    select_customer:{
    name:"未选择",
    card_number:"--",
    user_level_name:"--",
    mobile:"--",
    bi_date:"--",
    sex:"--",
    hkqd:"--",
    age:"--",
    created_at:"--",
    last_come:"--",
    record_hobby:[],
    totals:{
    weimei:0,
    cdp:0,
    fujia:0,
    other:0,
    buy_money:0,
    cases:0,
    appoint_count:0,
    return_count:0,
    operation_count:0,
    face_count:0,
    test_count:0,
    having_customers:0,
    customers_level5:0

    }
    },
    tab_goods:[],
    meeting_users:[],
    config:[],
    uploadAction: base_path+'/system/base/userimg',
    token: getToken(),
    pay:false,
    pay_data:[],
    payForm: {
      id:0,
      order_id:0,
      pay_type:3,
      images:[],
      images_pc:[]
    },
    get_jf_data:[],
    fjq:[],
    keyword:"",
    timeRange: [
        new Date(new Date().setDate(new Date().getDate() - 180)).setHours(0, 0, 0, 0), // 前15天 00:00:00
        new Date(new Date().setDate(new Date().getDate())).setHours(23, 59, 59, 999)  // 后15天 23:59:59.999
    ],
});

onMounted(() => {
  data.select_customer = props.infoData
  on_ref()
})


function on_ref(){
  get_order_list()
}

function formatDate(timestamp) {
  const date = new Date(timestamp);
  // 添加时区偏移（单位：分钟）
  const offset = date.getTimezoneOffset() * 60000; // 转为毫秒
  const localTime = new Date(date.getTime() - offset);
  return localTime.toISOString().replace('T', ' ').substring(0, 19);
}

function get_order_list(){
  data.card_loading = true
  api.getCases({
    user_id:data.select_customer.user_id,
    keyword:data.keyword,
    start: formatDate(data.timeRange[0]), // 开始日00:00:00
    end: formatDate(data.timeRange[1]), // 结束日23:59:59
  }).then((res) => {
     data.orders = res.data.items
     data.card_loading = false
     data.loading = false
  })
}

function handleNumsChange(value, item){
  dialog.warning({
    title: '警告',
    content: '你确定修改数量为'+value+'次吗',
    positiveText: '确定',
    negativeText: '取消',
    draggable: true,
    onPositiveClick: () => {
        api.updateCaseNums({
          id:item.id,
          nums:value,
        }).then((res) => {
          message.success("修改成功")
        })
    },
  })
}

function go_cancel(item){
  api.deleteCases({
    id:item.id,
  }).then((res) => {
    message.success('作废成功')
    on_ref()
  })
}

function search_order(){
  data.loading = true
  get_order_list()
}

function go_print(item){
  api.printCases({
    id:item.id,
  }).then((res) => {
    message.success('打印成功')
    on_ref()
  })
}

function handleTimeChange() {
  if(data.timeRange && data.timeRange.length === 2) {
    get_order_list()
  }
}

</script>
<template>
  <div class="container" style="height: calc(100vh - 106px);">
    <div class="search">
      <NInput   @change="search_order" v-model:value="data.keyword"  :loading="data.loading" clearable type="text" placeholder="请输入卡项,项目名称检索"/>
      <n-date-picker
        v-model:value="data.timeRange"
        type="daterange" style="margin-top: 10px"
        clearable
        @update:value="handleTimeChange"
      />
    </div>
     <n-spin :show="data.card_loading" style="--n-opacity-spinning:0.1;height: calc(100vh - 225px);">
       <n-scrollbar v-if="data.orders.length>0" style="max-height: calc(100vh - 180px);padding:0 20px 20px 0px">
          <n-collapse  class="cards" accordion :trigger-areas="['main']" :default-expanded-names="data.orders[0].id">
        <n-collapse-item :name="item.id" v-for="item in data.orders" class="card">
          <template #header>
            <div style="display: flex; align-items: center;justify-content: flex-start">
              <n-h6 prefix="bar" type="info" style="margin: 0;font-size: 16px">
                <div style="display: flex">
                <n-button type="info" dashed size="large">病例单号:{{item.id}}</n-button>
              <div style="height:40px;line-height:20px;margin-left: 10px">
                <span v-for="item2 in item.projects" style="margin-right: 5px">
                  {{item2.title}}<span style="font-size: 12px">X{{item2.num}}</span>
                </span>
                <br>
                <span style="font-size: 12px;color:#747586">操作于:{{item.created_at}}</span>
              </div>
                </div>
              </n-h6>
            </div>
          </template>
          <template #header-extra>
<!--            <n-button type="primary" dashed disabled >对比照{{item.image_staus}}</n-button>-->
            <n-popconfirm @positive-click="go_print(item)" v-if="item.is_print===0">
                <template #trigger>
                   <n-button type="primary" >
                     <TheIcon icon="material-symbols:print" :size="16" class="mr-5" />打印</n-button>
                </template>
                请确认病例,打印后将无法修改病例关键信息
              </n-popconfirm>

             <n-button type="primary" dashed  v-else>已打印</n-button>
          </template>

          <div class="project_list">
            <div style="display: flex;gap: 10px;">
                <n-card size="small" style="width: 400px;" :bordered="false" hoverable content-style="padding: 0px;" :segmented="{content: true,footer: 'soft',}">
                  <template #header><n-h6 prefix="bar" style="margin: 0;font-size: 14px">划扣详情</n-h6></template>
                  <template #footer>
                    <div>
                      <div class="item1" v-for="item2 in item.projects" style="display: flex; justify-content: space-between; align-items: center;">
                        <div class="text">{{item2.title}}</div>
                          <div>使用
                            <n-input size="tiny" style="width: 30px" v-model:value="item2.num" @keyup.enter="(e) => handleNumsChange(e.target.value, item2)" />次
                          </div>
                      </div>
                    </div>
                  </template>
                </n-card>

                <n-card size="small" style="width: 210px;" :bordered="false" hoverable content-style="padding: 0px;" :segmented="{content: true,footer: 'soft',}">
                  <template #header><n-h6 prefix="bar" style="margin: 0;font-size: 14px">参与人员</n-h6></template>
                  <template #footer>
                    <div>
                      <div class="item1">
                        <div class="text">录入:{{item.butler}}</div>
                        <div class="text">健康顾问:{{item.face_name}}</div>
                        <div class="text">医生:{{item.doctor_name}}</div>
                      </div>
                    </div>
                  </template>
                </n-card>
              <n-card size="small" style="width: 300px;" :bordered="false" hoverable content-style="padding: 0px;" :segmented="{content: true,footer: 'soft',}">
                  <template #header><n-h6 prefix="bar" style="margin: 0;font-size: 14px">术前协议</n-h6></template>
                  <template #footer>
                     <n-scrollbar x-scrollable>
                    <div style="display: flex">
                          <n-image style="height:100px;border-radius: 5px;margin-right: 2px"  :src="img" v-for="img in item.voucher_images"/>
                    </div>
                     </n-scrollbar>
                  </template>
                </n-card>

                <n-card size="small" style="flex:1" :bordered="false" hoverable content-style="padding: 0px;" :segmented="{content: true,footer: 'soft',}">
                  <template #header><n-h6 prefix="bar" style="margin: 0;font-size: 14px">备注</n-h6></template>
                  <template #footer>
                    <div>
                      {{item.remark}}
                    </div>
                  </template>
                </n-card>
            </div>
            <div style="margin-top: 10px">


              <n-popconfirm @positive-click="go_cancel(item)" v-if="item.is_print===0">
                <template #trigger>
                   <n-button  type="error" style="margin-right:10px">
                     <TheIcon icon="material-symbols:delete" :size="16" class="mr-5" />作废</n-button>
                </template>
                确定要作废该病例吗？
              </n-popconfirm>

            </div>

            </div>

        </n-collapse-item>
      </n-collapse>
      </n-scrollbar>
       <n-empty v-else description="暂无数据"  style="margin: 50px"></n-empty>
     </n-spin>

  </div>



</template>


<style>
 .container{
   padding: 10px;
   //transform: translate(0);
   position: relative;
   height:100%;
   .search{
     margin-bottom: 10px;
   }
 }
 .cards{
   margin:0px;
 }
 .project{margin-bottom: 10px;}
 .project_list{
   background: #f3f3f3;
   padding: 20px;
   border-radius: 5px;

 }
 .add_cases{
   height:60px;
   position: absolute;
   bottom: 0;
   background: #eee;
   width: 100%;
   padding: 10px;
   border-top-left-radius: 5px;
 }

</style>